package com.cooper.controllers;

import java.lang.annotation.Annotation;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.ControllerInterceptorAdapter;
import net.paoding.rose.web.Invocation;

import com.cooper.domain.UserSession;
import com.cooper.util.Controllers;

public class LoginRequiredInterceptor extends ControllerInterceptorAdapter {

    // 覆盖这个方法，表示只有标注@LoginRequired的控制器或方法才会被此拦截器拦截
    @Override
    public Class<? extends Annotation> getRequiredAnnotationClass() {
        return LoginRequired.class;
    }

    @Override
    public Object before(Invocation inv) throws Exception {
        HttpServletRequest request = inv.getRequest();
        // 在此，假设我们判断是否已经登录的方法是session是否存在
        // 当然，对于互联网应用来说，不能使用默认的这种session机制
        UserSession userSession = Controllers.getUserSession(inv);
        if (null == userSession || null == userSession.getUserInfo()) {
            // 如果没有登录，重定向到登录页面
        	String originURL = request.getRequestURL().toString();
            return "/login?originURL=" + originURL;
        }
        return true;
    }
}
